// 环境变量配置
require('dotenv').config();

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var helmet = require('helmet');
var rateLimit = require('express-rate-limit');
var session = require('express-session');
var SequelizeStore = require('connect-session-sequelize')(session.Store);

// 数据库连接
const db = require('./models');

// 路由引入
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var apiRouter = require('./routes/api');
var adminRouter = require('./routes/admin');

var app = express();

// 数据库初始化
db.testConnection();
if (process.env.NODE_ENV === 'development') {
  db.syncDatabase();
}

// 安全中间件
app.use(helmet({
  contentSecurityPolicy: false, // 禁用CSP以允许内联样式
  crossOriginResourcePolicy: { policy: "cross-origin" }
}));

// CORS配置
const { createCorsMiddleware, handlePreflight } = require('./middleware/cors');

// 处理预检请求
app.use(handlePreflight);

// 应用CORS中间件
app.use(createCorsMiddleware());

// 限流中间件
const limiter = rateLimit({
  windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 15 * 60 * 1000, // 15分钟
  max: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS) || 100, // 每个IP最多100个请求
  message: {
    error: '请求过于频繁，请稍后再试',
    code: 429
  },
  standardHeaders: true,
  legacyHeaders: false
});

app.use('/api', limiter);

// Session配置
const sessionStore = new SequelizeStore({
  db: db.sequelize,
  tableName: 'sessions',
  checkExpirationInterval: 15 * 60 * 1000, // 15分钟清理一次过期session
  expiration: 24 * 60 * 60 * 1000 // 24小时过期
});

app.use(session({
  secret: process.env.SESSION_SECRET || 'your-session-secret',
  resave: false,
  saveUninitialized: false,
  store: sessionStore,
  cookie: {
    secure: process.env.NODE_ENV === 'production',
    httpOnly: true,
    maxAge: 24 * 60 * 60 * 1000 // 24小时
  }
}));

// 同步session表
sessionStore.sync();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// 基础中间件
app.use(logger(process.env.NODE_ENV === 'production' ? 'combined' : 'dev'));
app.use(express.json({ 
  limit: '10mb',
  verify: (req, res, buf) => {
    req.rawBody = buf;
  }
}));
app.use(express.urlencoded({ 
  extended: false,
  limit: '10mb'
}));
app.use(cookieParser());

// 静态资源服务
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'public/uploads')));

// 路由配置
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/api', apiRouter);
app.use('/admin', adminRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
